package io.jft.doll.ui.home

import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.android.vlayout.LayoutHelper
import com.alibaba.android.vlayout.layout.LinearLayoutHelper
import com.g.base.extend.*
import com.g.base.help.observeSimpleNotify
import com.g.base.room.entity.UserEntity
import com.g.base.room.repository.Status
import com.g.base.router.BasePage
import com.g.base.token.TokenManage
import com.g.base.ui.BaseFragment
import com.g.base.ui.recyclerView.decoration.LinearItemDecoration
import com.g.base.ui.recyclerView.setupRecyclerView
import io.jft.doll.R
import io.jft.doll.databinding.FragmentHomeDrawerMenuBinding
import io.jft.doll.event.NotifyUrl
import io.jft.doll.model.bindModel.ImageTextTipBind
import io.jft.doll.model.viewModel.MessageViewModel
import io.jft.doll.model.viewModel.UserViewModel
import io.jft.doll.router.RouterPage
import io.jft.doll.ui.home.bind.UserDrawerHeaderItemBind

/**
 * Created by G on 2017/11/13 0013.
 */
class HomeDrawerMenuFragment : BaseFragment<FragmentHomeDrawerMenuBinding>() {

    override fun setContentView(): Int = R.layout.fragment_home_drawer_menu
    private val adapter by lazy { setupRecyclerView(contentView.recyclerView) }
    private val messageViewModel by lazy { ViewModelProviders.of(this).get(MessageViewModel::class.java) }
    private val userViewModel by lazy { ViewModelProviders.of(this).get(UserViewModel::class.java) }

    private val userHeader: UserDrawerHeaderItemBind by lazy { UserDrawerHeaderItemBind() }

    private val message by lazy { ImageTextTipBind("我的消息", R.drawable.ic_notifications_none_black_24dp, "", false) }

    private val recharge by lazy { ImageTextTipBind("娃娃币充值", R.drawable.ic_attach_money_black_24dp, "", false) }
    private val doll by lazy { ImageTextTipBind("我的娃娃", R.drawable.ic_insert_emoticon_black_24dp, "", false) }
    private val gameHistory by lazy { ImageTextTipBind("游戏记录", R.drawable.ic_change_history_black_24dp, "", false) }

    private val duiBar by lazy { ImageTextTipBind("积分商城", R.drawable.ic_card_giftcard_black_24dp, "", false) }
    private val inviteCode by lazy { ImageTextTipBind("我的邀请码", R.drawable.ic_bookmark_border_black_24dp, "", false) }
    private val inputInviteCode by lazy { ImageTextTipBind("输入邀请码", R.drawable.ic_input_black_24dp, "", false) }

    private val feedBack by lazy { ImageTextTipBind("反馈", R.drawable.ic_feedback_black_24dp, "", false) }

    private var lastItemClickTime = 0L

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        showContentView()
        setupView()

        observeSimpleNotify<Any?>(this, NotifyUrl.MessageCount) {
            messageViewModel.operateMessageCount()
            true
        }
        observeSimpleNotify<Any?>(this, NotifyUrl.UserRemaining) {
            userViewModel.operateRemain()
            true
        }

        obsData()
    }

    private fun obsData() {
        userViewModel.operateRemain()
        userViewModel.operateInviteInfo()
        messageViewModel.operateMessageCount()

        userViewModel.obsRemainingSum()
                .resultNotNull()
                .observeEx(this) {
                    when (it.status) {
                        Status.Loading -> userHeader.remaining.set("获取中")
                        Status.Content -> userHeader.remaining.set(it.data!!)
                        else -> userHeader.remaining.set("--")
                    }
                }

        userViewModel.obsInviteInfo()
                .resultNotNull()
                .observeEx(this) {
                    if (it.status == Status.Content) {
                        inviteCode.tip.set("已邀请${it.data!!.amount}人")
                    } else {
                        inviteCode.tip.set("已邀请0人")
                    }
                }

        messageViewModel.obsMessageCount().resultNotNull()
                .observeEx(this) {
                    if (it.status == Status.Content) {
                        message.badge.set(it.data)
                    }
                }
    }

    //Item点击事件 统一处理 关闭侧边栏 点击间隔
    private fun itemClickListener(exec: () -> Unit) {
        val currentTimeMillis = System.currentTimeMillis()
        if (currentTimeMillis - lastItemClickTime > 1000L) {
            exec()
        }
        lastItemClickTime = currentTimeMillis
    }

    private fun setupView() {
        adapter.renderItems.add(userHeader)
        adapter.renderItems.add(message)
        adapter.renderItems.add(recharge)
        adapter.renderItems.add(doll)
        adapter.renderItems.add(gameHistory)
        adapter.renderItems.add(duiBar)
        adapter.renderItems.add(inviteCode)
        adapter.renderItems.add(inputInviteCode)
        adapter.renderItems.add(feedBack)

        //设置RecyclerView
        val layoutHelpers = arrayListOf<LayoutHelper>()
        val top0 = LinearLayoutHelper(0, 1)
        layoutHelpers.add(top0)
        val top1 = LinearLayoutHelper(0, 1)
        layoutHelpers.add(top1)
        val top2 = LinearLayoutHelper(0, 3)
        layoutHelpers.add(top2)
        val top3 = LinearLayoutHelper(0, 3)
        layoutHelpers.add(top3)
        val top4 = LinearLayoutHelper(0, 1)
        layoutHelpers.add(top4)
        top2.marginTop = 8.dp()
        top3.marginTop = 8.dp()
        top4.marginTop = 8.dp()

        adapter.layoutHelpers = layoutHelpers
        contentView.recyclerView.addItemDecoration(LinearItemDecoration(context!!, 1))
        adapter.notifyDataSetChanged()

        message.setOnClickListener {
            itemClickListener {
                ARouter.getInstance().build(RouterPage.MessageActivity).navigation(activity)
            }
        }

        recharge.setOnClickListener {
            itemClickListener {
                ARouter.getInstance().build(RouterPage.RechargeActivity).navigation(activity)
            }
        }

        doll.setOnClickListener {
            itemClickListener {
                val token = TokenManage.getToken()
                ARouter.getInstance().build(RouterPage.DollActivity)
                        .withString("userName", token?.nickName)
                        .withString("thumbnail", token?.headerImage)
                        .navigation(activity)
            }
        }

        gameHistory.setOnClickListener {
            itemClickListener {
                ARouter.getInstance().build(RouterPage.GameHistoryActivity).navigation(activity)
            }
        }

        duiBar.setOnClickListener {
            itemClickListener {
                userViewModel.getDuiBarAddress()
                        .resultNotNull()
                        .observeExOnce(activity as LifecycleOwner) {
                            when (it.status) {
                                Status.Content -> ARouter.getInstance().build(RouterPage.WebViewActivity).withString("url", it.data!!).navigation(activity)
                                Status.Error -> toast(it.error?.message ?: "未知错误~")
                            }
                        }
            }
        }


        inviteCode.setOnClickListener {
            itemClickListener {
                ARouter.getInstance().build(RouterPage.InviteCodeActivity).navigation(activity)
            }
        }

        inputInviteCode.setOnClickListener {
            itemClickListener {
                ARouter.getInstance().build(RouterPage.InputInviteCodeActivity).navigation(activity)
            }
        }

        feedBack.setOnClickListener {
            itemClickListener {
                ARouter.getInstance().build(RouterPage.FeedBackActivity).navigation(activity)
            }
        }

        //设置页面
        contentView.setting.setOnClickListener {
            itemClickListener {
                ARouter.getInstance().build(RouterPage.SettingActivity).navigation(activity)
            }
        }

        //退出
        contentView.quit.setOnClickListener {
            itemClickListener {
                (activity as HomeActivity).finishAfterTransition()
            }
        }

        //侧滑的个人信息展示
        onTokenChange(TokenManage.getToken())
    }

    override fun onTokenChange(data: UserEntity?) {
        if (data == null) {
            setupUnOauth()
        } else {
            setupOnOauth(data)
        }
    }


    private fun setupUnOauth() {
        inviteCode.tip.set("")
        userHeader.apply {
            headerImage.set("")
            placeholder.set(R.drawable.ic_default_head_portrait_man)
            username.set("请先登录")
            remaining.set("-1")
            setOnClickListener { ARouter.getInstance().build(BasePage.Oauth).navigation(activity) }
        }
    }

    private fun setupOnOauth(data: UserEntity) {
        userViewModel.operateRemain()
        userViewModel.operateInviteInfo()
        userHeader.apply {
            headerImage.set(data.headerImage)
            placeholder.set(
                    if (data.sex == "男") {
                        R.drawable.ic_default_head_portrait_man
                    } else {
                        R.drawable.ic_default_head_portrait_female
                    }
            )
            username.set(data.nickName)
            setOnClickListener { }
        }
    }
}